package com.example.beat_x3.Fragments;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.beat_x3.Adapter.HomeAdapter;
import com.example.beat_x3.Client.GetResult;
import com.example.beat_x3.R;

import Entity.Inf;
import Entity.Reservations;

public class HomeFragment extends MyFragment {
    private HomeAdapter homeAdapter;
    private final Handler myHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) homeAdapter.refresh();
        }
    };

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, null);
        RecyclerView recyclerView = view.findViewById(R.id.home_reservations);
        SwipeRefreshLayout refreshLayout = view.findViewById(R.id.home_refresh);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
                myHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refreshLayout.setRefreshing(false);
                    }
                }, 1000);
            }
        });
        homeAdapter = new HomeAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(Inf.context));
        recyclerView.setAdapter(homeAdapter);
        refresh();
        return view;
    }

    public void refresh() {
        new RefreshThread().start();
    }

    class RefreshThread extends Thread {
        @Override
        public void run() {
            Reservations reservations = GetResult.QueryReservation();
            if (reservations != null) {
                homeAdapter.reservations = reservations.reservations;
                myHandler.sendEmptyMessage(0);
            }
        }
    }
}